// websocket.js
const websocket = {
    ws: null,
    isSocketOpen: false,
    setWs: function (newWs) {
        this.ws = newWs;
    },
    setStatus: function (newStatus) {
        this.isSocketOpen = newStatus;
    },
    // 发送消息
    async sendMessage(message) {
        // 检查 WebSocket 连接状态
        if (this.ws.readyState !== 1) {
            // 重新连接 WebSocket
            await this.init();
            // 等待 WebSocket 连接成功
            await new Promise((resolve) => {
                const checkSocketOpen = () => {
                    if (this.ws.readyState === 1) {
                        resolve();
                    } else {
                        setTimeout(checkSocketOpen, 100);
                    }
                };
                checkSocketOpen();
            });
        }
        this.ws.send(JSON.stringify(message));
    },
};

export default websocket;
